package pl.matt.media.extractor.impl;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Collection;

import pl.matt.media.manager.MediaManagersFactory;
import pl.matt.media.manager.ObjectsDetectorManager;
import pl.matt.media.manager.impl.ObjectsDetectorManagerImpl;
import pl.matt.media.model.ImageType;
import pl.matt.model.Rectangle;

/**
 * wyodrębnia wszystkie twarze z klatki
 * 
 * @author mateusz
 * 
 */
public class AllFacesExtractor {

	@SuppressWarnings("unused")
	private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(AllFacesExtractor.class);
	
	private String facesDirectory = "/tmp/frames2/";
	private String imageExtension = ".jpg";
	private String faceNamePrefix = "face";
	
	private ObjectsDetectorManager objectsDetectorManager = new ObjectsDetectorManagerImpl();
	
	public AllFacesExtractor() {
		
	}
	
	public AllFacesExtractor(String facesDirectory) {
		this.facesDirectory = facesDirectory;
	}
	

	public void extract() throws IOException {
		File directory = new File(facesDirectory);
		String[] files = directory.list(new FilenameFilter() {
			public boolean accept(File dir, String name) {
				return name.toLowerCase().endsWith(imageExtension);
			}
		});
		for (int i = 0; i < files.length; i++) {
			String frameFileName = facesDirectory + File.separator + files[i];
			Collection<Rectangle> faces = objectsDetectorManager.detectFaces(frameFileName);
			int index = 0;
			for (Rectangle rectangle : faces) {				
				String name = facesDirectory + File.separator + faceNamePrefix + "_" + index++ + "_" + files[i];
				MediaManagersFactory.getImageManager().cropImage(frameFileName, name, rectangle, ImageType.JPEG);
			}
		}
	}

	public static void main(String[] args) throws IOException {
		AllFacesExtractor extractor = new AllFacesExtractor("resources/images/testFaces");
		extractor.extract();
		
	}
	
}
